<script lang="ts" setup>
  import { ref, onMounted, computed } from 'vue';
  import { Form, Message } from '@arco-design/web-vue';
  import {
    createGameGroup,
    updateGameGroup,
    getGameNotGroupUsers,
  } from '@/api/game';
  import { User } from '@/types/user';
  import { GameGroup } from '@/types/game';

  const props = defineProps<{
    gameId: string;
    gameGroup?: GameGroup;
  }>();

  const emit = defineEmits(['close']);

  const notGroupUsers = ref<User[]>([]);

  const availableGroupUsers = computed(() => {
    if (props.gameGroup) {
      return [...props.gameGroup.users, ...notGroupUsers.value];
    }
    return notGroupUsers.value;
  });

  const data = ref<{
    gameId: string;
    groupName: string;
    auto: number;
    startTime: string;
    userIds: string[];
  }>({
    gameId: props.gameId,
    groupName: '',
    startTime: '',
    auto: 0,
    userIds: [],
  });

  onMounted(async () => {
    if (props.gameGroup) {
      // @ts-ignore
      data.value = {
        ...props.gameGroup,
      };
    }
    try {
      const res = await getGameNotGroupUsers(props.gameId);
      notGroupUsers.value = res.data.data || [];
    } finally {
      // do nothing
    }
  });

  const formRef = ref<InstanceType<typeof Form> | null>(null);

  const saving = ref(false);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validate = await formRef.value.validate();
      if (!validate) {
        try {
          saving.value = true;
          if (props.gameGroup) {
            await updateGameGroup(data.value);
            Message.success('编辑成功');
          } else {
            await createGameGroup(data.value);
            Message.success('创建成功');
          }
          emit('close', true);
        } finally {
          saving.value = false;
        }
      }
    }
  };
</script>

<template>
  <a-modal
    :title="gameGroup ? '编辑分组' : '新建分组'"
    :width="600"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <div class="editor">
      <a-form ref="formRef" :model="data" layout="vertical">
        <a-form-item
          label="组名"
          field="groupName"
          :rules="[{ required: true, message: '请输入组名' }]"
        >
          <a-input
            v-model="data.groupName"
            placeholder="请输入组名"
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="开球时间" field="startTime">
          <a-time-picker v-model="data.startTime" format="HH:mm" />
        </a-form-item>

        <a-form-item v-if="!gameGroup" label="是否自动分配球员" field="auto">
          <a-radio-group
            v-model="data.auto"
            :options="[
              { value: 0, label: '手动分配' },
              { value: 1, label: '自动分配' },
            ]"
          />
        </a-form-item>

        <a-form-item
          v-if="data.auto === 0 && !gameGroup"
          label="组内球员"
          field="userIds"
        >
          <a-transfer
            v-model="data.userIds"
            :data="
              availableGroupUsers.map((i) => ({
                label: i.nickname,
                value: i.id,
                disabled: false,
              }))
            "
            style="flex: 1"
            show-search
            :source-input-search-props="{ placeholder: '搜索球员名字' }"
            :target-input-search-props="{ placeholder: '搜索球员名字' }"
          >
            <template #source-title="{ countTotal }">
              待分组球员({{ countTotal }})
            </template>
            <template #target-title="{ countTotal }">
              组内球员({{ countTotal }})
            </template>
            <template #item="{ value }">
              <div>
                <div>
                  {{
                    availableGroupUsers.find((i) => i.id === value)?.nickname
                  }}
                </div>
                <div>
                  {{ availableGroupUsers.find((i) => i.id === value)?.phone }}
                </div>
              </div>
            </template>
          </a-transfer>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<style lang="less" scoped>
  .editor {
    &:deep(.arco-transfer-view) {
      flex: 1;
      min-width: 0;
    }
    &:deep(.arco-transfer-list-item) {
      height: 50px;
      .arco-checkbox {
        line-height: 20px;
      }
    }
  }
</style>
